<template>
  <el-dialog title="添加BANNER"  :close-on-click-modal="false" id="addbanner" :visible.sync="show" 
  class="addBanner dialog_index dialog_banner" :before-close="cancle"  >
   <el-form ref="bannerForm" class="scroll" v-loading="loading">
      <el-tabs type="card" v-model="activeName" >
        <el-tab-pane  :label="item.site" :name="item.site" v-for="(item, index)  in formList" :key="item.id">
            <el-upload class="upload-banner" action="/api/api/general/upload" 
            :on-success="(response, file, fileList) => handleBannerSuccess(response, file, fileList, item)"
             :on-error="handleBannerError" :before-upload="beforeBannerUpload"
            :show-file-list="false" :accept="fileType" :data="{type:'banner', imageheight: imgH, imagewidth: imgW}" >
              <el-button size="small" type="primary" @click="chooseGallery(index)">图库选择</el-button>
              <el-button slot="trigger" size="small" type="primary">本地上传</el-button>
              <el-popover placement="bottom-start" width="228" trigger="click" ref="popover" :append-to-body="false" popper-class="popover_video">
                <el-button slot="reference">视频链接</el-button>
                <template >
                  <p class="popover_video_title">视频链接</p>
                  <el-input v-model="item.video_url"></el-input>
                  <div class="popover_video_btn">
                    <el-button type="search" @click="setImageUrl(item, index)">确定</el-button>
                  </div>

                </template>
              </el-popover>
               <div class="banner_tip">
                <p class="tip">图片建议上传.jpg/.jpeg格式，且尺寸为1920*937px，大小≤2M</p>
                <p class="tip2">视频建议上传.mp4,.3GP,.MOV格式，大小≤10M</p>
              </div>
              <div class="pop_container">
                <img v-show="item.image" :src="utils.setCdnUrl() + item.image" class="pop_image" >
              </div>
            </el-upload>
            <p class="banner_title">BANNER设置</p>
            <el-form-item label="BANNER形式：">
              <el-radio-group v-model="item.banner_type" @change="value => changeBannerType(value,item)">
                <el-radio label="1">一个BANNER多个站点</el-radio>
                <el-radio label="2">多个BANNER多个站点</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="一级标题：">
              <el-input  :placeholder="'一级标题('+item.site+')（非必填项)'" v-model="item.first_title"></el-input>
            </el-form-item>
            <el-form-item label="二级标题：">
              <el-input :placeholder="'二级标题('+item.site+')（非必填项)'" v-model="item.second_title"></el-input>
            </el-form-item>
            <p class="banner_title">关联产品或文章</p>
            <el-form-item label="关联类型：">
              <el-select v-model="item.relation_type" placeholder="关联类型（必填项）" @change="value => changeRelationType(value, item)">
                <el-option v-for="item in associationTypeList" :key="item.value"  :label="item.label"  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="关联内容："  >
              <el-radio-group v-model="item.association_types" :disabled="item.relation_type === 1"
               @change="value => changeAssociationType(value,item)">
                <el-radio :label="0">关联产品</el-radio>
                <el-radio :label="1">关联文章</el-radio>
                <el-radio :label="2">自定义链接</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="关联产品：" v-if="item.association_types === 0">
              <el-select v-model="item.product_id" :popper-append-to-body="false" :disabled="item.relation_type === 1" placeholder="关联产品（必填项）"
               @change="value => changeProduct(value,item)"    @focus="(event) => getProductSelectList(event, item)" >
                <el-option v-for="product in item.relationProductList" :key="product.value"  :label="product.label"  :value="product.product_id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="关联文章：" v-if="item.association_types === 1">
              <el-select v-model="item.association_types_name" :popper-append-to-body="false" placeholder="关联文章（必填项）" :disabled="item.relation_type === 1" 
              @change="value => changeArticle(value,item)"    @focus="(event) => getArticleSelectList(event, item)">
                <el-option v-for="product in relationArticleList" :key="product.value"  :label="product.label"  :value="product.value"></el-option>
              </el-select>
            </el-form-item>
             <el-form-item label="自定义链接：" v-if="item.association_types === 2">
              <el-input :placeholder="'自定义链接('+item.site+')（必填项)'"  @change="value => changeArticle(value,item)" 
               v-model="item.association_types_name"></el-input>
            </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="search" @click="submitForm" :loading="isSubmit">保存</el-button>
      <el-button @click="cancle">取消</el-button>
    </span>
    <Drawer v-show="showDrawer" :type="'banner'" :show="showDrawer"  @closeDialog="closeDrawerDialog"></Drawer>
   </el-dialog>
</template>

<script>
import { siteListGet } from '@/api/manage/site.js'
import { extendObj, checkFile } from '@/utils/index'
import { bannerAdd } from '@/api/index/banner.js'
import { productSelectList, articleSelectList } from '@/api/product/productBasic.js'
import Drawer  from '@/components/Gallery/index.vue' 

export default {
  data () {
    return {
      formList:[],
      imgH:'',
      imgW:'',
      loading: false,
      activeName: 'us',
      associationTypeList: [
        {value: 1, label: '无关联'},
        {value: 2, label: '统一关联'},
        {value: 3, label: '分别关联'},
      ],
      relationArticleList: [],
      showDrawer: false,
      cur_index: 0,
      isSubmit: false,
      fileType: '.jpg,.jpeg,.mp4,.3GP,.MOV'
    }
  },
  props: {
    show: Boolean,
    closeDialog:Function,
  },
  watch: {
    show:function(){
      if(this.show){
        this.loading = true
        this.getSite()
      }
    }
  },
  components: { Drawer },
  methods: {
    chooseGallery (index) {
      this.showDrawer = true
      this.cur_index = index
    },
      // 图库选择是否显示
    closeDrawerDialog (data) {
      this.showDrawer = !this.showDrawer
      if (data && data.filePathName) { 
        let cur_item = this.formList[this.cur_index]
        cur_item.image = data.filePathName
        cur_item.httpImage = data.filePathNameHttp
        this.changeBannerType(cur_item.banner_type, cur_item)
      }
    },
    getArticleSelectList() {
      articleSelectList().then(res=>{
        this.relationArticleList = res.data
      })
    },
    getProductSelectList (event,item) {
      let params = {
        site_id: item.site_id
      }
      productSelectList(params).then(res=>{
        item.relationProductList = res.data
      })
    },
    //  关联类型改变
    changeRelationType (value, item) {
      let list = this.formList
      if (value == 2){
        // 统一关联
        for (let i = 0; i < list.length; i++){
          list[i].relation_type = value
          list[i].association_types = item.association_types
          list[i].product_id = item.product_id
          list[i].association_types_name = item.association_types_name

        }
      } else if (value == 3){
        // 分别关联
        for (let i = 0; i < list.length; i++){
          list[i].relation_type = value
          list[i].association_types = item.association_types
        }
      } else {
        // 无关联
        for (let i = 0; i < list.length; i++){
          list[i].relation_type = value
        }
      }
      this.formList = list
     
    },
    // 关联内容
    changeAssociationType (value) {  // 关联内容改变 之前选择的清空
      let list = this.formList
      for (let i = 0; i < list.length; i++){
        list[i].association_types = value
        list[i].product_id = ''
        list[i].association_types_name = ''
      }
      this.formList = list
    },
    changeProduct (value, item) {
      let list = this.formList
      if (item.relation_type == 2){
        for (let i = 0; i < list.length; i++){
          list[i].product_id = value
        }
      }
      this.formList = list
    },
    changeArticle (value,item) {
      let list = this.formList
      if (item.relation_type == 2){
        for (let i = 0; i < list.length; i++){
          list[i].association_types_name = value
        }
      } 
      this.formList = list
    },
    
    changeBannerType (value, item) {
       let bannerList = this.formList
      if(value == 1){
        // 一个个BANNER多个站点
        for(let i = 0; i < bannerList.length; i++){
          bannerList[i].image = item.image
          bannerList[i].httpImage = item.httpImage
          bannerList[i].video_url = item.video_url
        }
      } 
      for(let i = 0; i < bannerList.length; i++){
        bannerList[i].banner_type = item.banner_type
      }
      this.formList = bannerList
    },
    handleBannerSuccess (response, res, fileList, item) {
      let path = response.data.filePathName 
      if(this.isVideo(path)){
        item.video_url = response.data.filePathName
        item.image = response.data.filePathNameHttp
        item.httpImage =  this.utils.setCdnUrl() +  response.data.filePathNameHttp
      } else if(this.isPicture(path)){
        item.image = response.data.filePathName
        item.httpImage =  this.utils.setCdnUrl() +  response.data.filePathNameHttp 
        item.video_url = ""
      }
      
      if(item.banner_type == 1){
        this.changeBannerType(1, item)
      }
      this.$message.success('上传成功')   
    },
    
    handleBannerError(){
      this.$message.error('上传失败')   
    },
    beforeBannerUpload(file){
      let isPicture = this.isPicture(file.name)
      let isVideo = this.isVideo(file.name)
      let that = this
      if(isPicture) { // 图片
        const isLt2M = file.size / 1024  <=  2048;
        if(!isLt2M){
          this.$message.error("上传图片大小不超过2M")
          return false
        }
        const isSize = new Promise(function(resolve, reject){
          let _URL = window.URL || window.webkitURL;
          let img = new Image();
          img.onload = function() {
             let valid = true
            that.imgW = img.width
            that.imgH = img.height
            valid ? resolve() : reject();
          }
          img.src = _URL.createObjectURL(file);
        }).then(()=>{

          return file
        }, ()=>{
          that.$message.error('上传图片尺寸为1920*937px')
          return Promise.reject()
        })
        return isSize
      } else if(isVideo){ // 视频
        const isLt2M = file.size / 1024  <=  40*1024;
        if(!isLt2M){
          this.$message.error("上传图片大小不超过40M")
          return false
        }
        return file

      } else {
        this.$message.error("仅支持.jpg/.jpeg格式的图片或者.mp4/.MOV/.3GP的视频")
        return false
      }
     
    },
  
    getSite (){
      siteListGet().then(res=>{
        if (res.status == 200) {
          let data = res.data
          for(let i = 0; i < data.length; i++){
            let obj = {
              image: '',
              first_title: '',
              second_title	: '',
              site_id: data[i].id,
              association_types: 0,
              association_types_name: '',
              association_types_id: '',
              banner_type: '1',
              httpImage:'',
              relation_type: 2,
              first_title_font_color: '#000000',
              first_title_font_size: '24',
              first_title_font_position_up: '10',
              first_title_font_position_left: '7.5',
              second_title_font_color: '#000000',
              second_title_font_size: '18',
              second_title_font_position_up: '20',
              second_title_font_position_left: '7.5',
              carousel_time: '10',
              relationProductList: [],
              product_id: null,
              video_url: ''
            }
            extendObj(data[i], obj)
            this.getProductSelectList(null, data[i])
            if ( i == 0 ){
              this.activeName = data[i].site
            }
          }
          this.getArticleSelectList ()

          this.formList= data
          this.loading = false
          let dialogBody = this.$el.querySelector('#addbanner .el-dialog__body')
          dialogBody.scrollTop = 0
        }

      })
    },
    submitForm () {
      let status = this.validateForm()
      if(status){
        this.addBanner()
      } 
    },
    validateForm () {
      let list = this.formList
      let status = true
      for ( let i = 0; i < list.length; i++ ){
        if (list[i].image === '' && list[i].video_url == "") {
          this.$message.error('站点' + list[i].site + '图片或视频为必填项')
          status = false
          break
        }
        if (list[i].first_title.length > 200) {
          this.$message.error('站点' + list[i].site + '一级标题最多200字符')
          status = false
          break
        }
        if (list[i].second_title.length > 200) {
          this.$message.error('站点' + list[i].site + '二级标题最多200字符')
          status = false
          break
        }
        if (list[i].relation_type === '') {
          this.$message.error('站点' + list[i].site + '关联类型为必填项')
          status = false
          break
        }
        if ( list[i].relation_type !== 1) {
           let product_id = list[i].product_id === null || list[i].product_id === ''
          if(list[i].association_types == 0 && product_id){
            //关联产品
            this.$message.error('站点' + list[i].site + '关联产品为必填项')
            status = false
            break
          } else  if(list[i].association_types == 1 && !list[i].association_types_name){
            //关联文章
            this.$message.error('站点' + list[i].site + '关联文章为必填项')
            status = false
            break
          } else  if(list[i].association_types == 2 && !list[i].association_types_name){
            //自定义链接
            this.$message.error('站点' + list[i].site + '自定义链接为必填项')
            status = false
            break
          }
          
        }
      }
      return status
    },
    addBanner () {
      this.isSubmit = true
      let list = this.formList
      for(let i = 0;i < list .length; i++){
        if(list[i].relation_type !== 1 ){
          if(list[i].association_types == 0){
            // 产品
            let productList = list[i].relationProductList 
            for(let j = 0; j< productList.length; j++){
              if(list[i].product_id == productList[j].product_id){
                list[i].association_types_id = productList[j].id
                list[i].association_types_name = productList[j].label
              }
            }
          } else {
            // 关联文章
            let productList = this.relationArticleList
            for(let j = 0; j< productList.length; j++){
              if(list[i].product_id == productList[j].value){
                list[i].association_types_id = productList[j].value
                list[i].association_types_name = productList[j].label
                list[i].product_id = null
              }
            }
          }
        }
      }
      let params = {
        data: JSON.stringify(list) 
      }
      bannerAdd(params).then(res => {
        if(res.state == 1){
          this.$message.success('保存成功')   
          this.cancle()
        }
         this.isSubmit  = false
      })
    },
    cancle(){
      this.$refs.bannerForm.resetFields(); // 清空原来的数据
      this.$emit('closeDialog')
      this.isSubmit  = false

    },
    videoUrl: function(item){ //解决视频地址更新 视频不更新的问题
      let html = ` <video class="video-player" id="upvideo" x5-video-player-type="h5" x-webkit-airplay="true"  webkit-playsinline="true"
                  playsinline="" poster="`+item.httpImage+`"  preload="none" autoplay="" loop="" >
                  <source src="`+item.video_url+`" />
                 </video>`
      return html
    },
    isPicture(url){
      if(url){
        return  checkFile(url, 'image', 'jpeg|jpg')
      } else {
        return false
      }
      
    },
    isVideo(url){
      if(url){
        return checkFile(url, 'video', 'MP4|MOV|3GP')
      } else {
        return false
      }
    },
    setImageUrl(item, index){ //视频链接点击
      item.image = ""
      item.httpImage = ""
      if(item.banner_type == 1){
        this.changeBannerType(1, item)
      }
      this.$refs['popover'][index].doClose()

    },

  },
  
 
}
</script>

<style>

</style>